package cn.net.ecode.util;

import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class FileUploadUtils {

    /**
     * 文件上传共用类
     *
     * @param file       文件
     * @param uploadPath 上传路径
     * @param type       上传类型（上传到的文件夹）
     * @return
     * @throws IOException
     */
    public static String fileUpload(MultipartFile file, String uploadPath, String type) throws IOException {
        String imageUrl = "";

        if (!file.isEmpty()) {
            String fileRealName = file.getOriginalFilename();
            int pointIndex = fileRealName.indexOf(".");
            String fileSuffix = fileRealName.substring(pointIndex);
            UUID FileId = UUID.randomUUID();
            String savedFileName = FileId.toString().replace("-", "").concat(fileSuffix);
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) {
                path = new File("");
            }
            File savedDir = new File(path.getAbsolutePath(), uploadPath + type + "/");
            if (!savedDir.exists()) {
                savedDir.mkdirs();
            }
            File savedFile = new File(savedDir, savedFileName);
            boolean isCreateSuccess = savedFile.createNewFile();
            if (isCreateSuccess) {
                file.transferTo(savedFile);
            }
            imageUrl = "/" + uploadPath + type + "/" + savedFileName;

        }

        return imageUrl;
    }
}
